<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import {
  ElButton,
  ElMessage,
  // ElTag,
  ElMessageBox,
  ElNotification
} from 'element-plus'

import { Table } from '@/components/Table'

// import { adminFaPastureEditApi } from '@/api/fa/pasture'

import { useTable } from '@/hooks/web/useTableTest'
import {
  // h,
  ref,
  unref,
  reactive,
  h
} from 'vue'
import Edit from './components/Edit.vue'
import See from './components/See.vue'
import Add from './components/Add.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useIcon } from '@/hooks/web/useIcon'

// 获取字典
import { useCache } from '@/hooks/web/useCache'
import {
  spForageInOutOrderDelApi,
  spForageInOutOrderEndApi,
  spForageInOutOrderListApi,
  spForageInOutOrderAddAdminApi,
  spForageInOutOrderEditApi,
  dbForageInOutOrderDetailedportApi
  // spForageInOutRfidBatchAddApi
} from '@/api/cy/FoodGoTo'
import { spForageSpecsSeeApi } from '@/api/cy/DrugGoTo'
import { zcPastureListAdminApi } from '@/api/fa/pasture'
// import { spForageInOutOrderAddAdminApi, spForageInOutOrderListApi } from '@/api/cy/FoodGoTo'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  // console.log(type)
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

const iconEdit = useIcon({ icon: 'ep:edit' })

const iconSee = useIcon({ icon: 'ep:view' })
const iconDelete = useIcon({ icon: 'material-symbols:delete-outline' })
const iconCompleted = useIcon({ icon: 'fluent-mdl2:completed' })
const iconExport = useIcon({ icon: 'bxs:file-export' })

const iconEnter = useIcon({
  icon: 'streamline:interface-login-circle-arrow-enter-left-login-point-circle'
})
const iconGo = useIcon({
  icon: 'streamline:interface-logout-circle-arrow-enter-right-logout-point-circle'
})
const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: spForageInOutOrderListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList, setSearchParams } = methods

getList()

const { t } = useI18n()
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'pasture_org_id',
    label: '牧场名称',
    width: 150,
    search: {
      component: 'DialogRefer',
      componentProps: {
        getListApi: zcPastureListAdminApi,
        response: { count: 'count', data: 'data' },
        title: '选择创建人（双击选择）',
        nameField: 'pasture_org_name',
        relNameField: 'org_name',
        valueField: 'org_id',
        crudSchemas: [
          { field: 'org_name', label: '牧场名称', search: { show: true } }
          // { field: 'org_id', label: '牧场ID', search: { show: true } }
        ]
      },
      show: true
    },
    table: {
      show: false
    }
  },
  {
    field: 'pasture_org_name',
    label: '所属牧场',
    width: 200,
    search: {
      show: false
    }
  },
  {
    field: 'code',
    label: '饲料出入库编号',
    width: 150,
    search: {
      show: true
    }
  },
  // {
  //   field: 'number',
  //   label: '出库数量',
  //   width: 150,
  //   search: {
  //     show: true
  //   }
  // },
  {
    field: 'type',
    label: '类型',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('in_out_type', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.in_out_type
      },
      show: true
    },
    table: {
      show: true
    }
  },
  {
    field: 'out_type',
    label: '出库类型',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('out_type', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.out_type
      },
      show: true
    },
    table: {
      show: true
    }
  },
  {
    field: 'in_type',
    label: '入库类型',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('in_type', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.in_type
      },
      show: true
    },
    table: {
      show: true
    }
  },
  {
    field: 'operate_name',
    label: '采购/领用人',
    width: 150
  },
  {
    field: 'sum_number',
    label: '总数量',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'create_time',
    label: '创建时间',
    width: 200,
    form: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'note',
    label: '备注',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'create_user_name',
    label: '创建人',
    width: 80,
    form: {
      show: false
    }
  },
  {
    field: 'action',
    width: 250,
    fixed: 'right',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

// 删除
const apiDel = async (id) => {
  let delRes = await spForageInOutOrderDelApi({ id })
    .catch(() => {})
    .finally(() => {})
  if (delRes) {
    getList()
  }
}

// 归档
const apicheck = async (id) => {
  let delRes = await spForageInOutOrderEndApi({ id })
    .catch(() => {})
    .finally(() => {})
  if (delRes) {
    getList()
  }
}
const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const actionType = ref('')

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑主表'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'ming':
      dialogTitle.value = '编辑明细'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {
        is_stop: '0'
      }
      // tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      ElMessageBox.confirm('确定要删除这个出入库单吗？', '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          console.log(row.id)
          apiDel(Number(row.id))
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    case 'shen':
      dialogTitle.value = '归档前最后确认'
      tableObject.currentRow = row
      dialogVisible.value = true
      // ElMessageBox.confirm('确定要归档吗？', '审核', {
      //   confirmButtonText: '确认',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      //     console.log(row.id)
      //     apicheck(Number(row.id))
      //   })
      //   .catch(() => {
      //     console.log('这里是取消confirm弹框')
      //   })
      break
    case 'export':
      // console.log(row, '导出')
      // break
      let { data }: any = await dbForageInOutOrderDetailedportApi({
        request: {
          forage_in_out_order_id: row.id,
          pageNo: 1,
          pageSize: '10000'
        },
        layout_data: {
          file_name: '饲料出入库明细列表',
          column_cell_start: 'A2',
          column_data: [
            {
              title: '序号',
              width: 5,
              cell_type: 'key'
            },
            {
              title: '牧场名称',
              width: 22,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'pasture_name'
            },
            {
              title: '饲料出入库编号',
              width: 20,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'code'
            },
            {
              title: '出入库类型',
              width: 12,
              cell_type: 'dict',
              dict_type: 'in_out_type',
              give_type: 'variable',
              give_value: 'type'
            },
            {
              title: '入库类型',
              width: 10,
              cell_type: 'dict',
              dict_type: 'in_type',
              give_type: 'variable',
              give_value: 'in_type'
            },
            {
              title: '出库类型',
              width: 10,
              cell_type: 'dict',
              dict_type: 'out_type',
              give_type: 'variable',
              give_value: 'out_type'
            },
            {
              title: '状态',
              width: 6,
              cell_type: 'dict',
              dict_type: 'forage_out_in_state',
              give_type: 'variable',
              give_value: 'state'
            },
            {
              title: '饲料档案名称',
              width: 15,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'forage_name'
            },
            {
              title: '饲料规格名称',
              width: 15,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'forage_specs_name'
            },
            {
              title: '申请数量',
              width: 10,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'apply_number'
            },
            {
              title: '实际数量',
              width: 10,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'actual_number'
            },
            {
              title: '采购金额',
              width: 12,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'amount'
            },
            {
              title: '操作人',
              width: 15,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'operate_name'
            },
            {
              title: '创建人',
              width: 15,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'create_user_name'
            },
            {
              title: '创建时间',
              width: 20,
              cell_type: 'datetime',
              give_type: 'variable',
              give_value: 'create_time'
            }
          ],
          custom: [
            {
              cell_type: 'string',
              cell: 'A1:O1',
              give_type: 'format',
              give_value: '饲料出入库明细列表',
              horizontal: 'center',
              border: true,
              size: '16'
            }
          ]
        }
      })
        .catch(() => {})
        .finally(() => {
          // saveLoading.value = false
        })
      if (data) {
        window.open(data.url)

        // console.log(data, Math.ceil(data.count / 10000))
        // FormsNumber.value = Math.ceil(data.count / 10000)
      }
      break
    default:
      console.log('未知类型')
  }
}

const editRef = ref<ComponentRef<typeof Edit>>()
const loading = ref(false)
const ADDtrue = ref(true)

const userInfo: any = wsCache.get('userInfo')
const save = async () => {
  const edit = unref<any>(editRef)
  switch (actionType.value) {
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          // const data = await edit?.methods?.getFormData()
          let formData = await edit?.methods?.getFormData()
          console.log('3333', edit, formData)
          let res = await spForageInOutOrderEditApi({
            id: formData.id,
            pasture_org_id: formData.pasture_org_id,
            pasture_dept_id: formData.pasture_dept_id,
            operate_id: formData.operate_name,
            note: formData.note
          })
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    case 'shen':
      console.log(await edit.id, 'uu')
      ElMessageBox.confirm('确定要归档吗？', '审核', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // console.log(row.id)
          apicheck(Number(await edit.id))
          dialogVisible.value = false
          tableObject.currentPage = 1
          getList()
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })

      break

    case 'add':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          let formData = await edit?.methods?.getFormData()
          console.log(edit, formData, 'ee')
          for (let index = 0; index < formData.detailed.length; index++) {
            if (!formData.detailed[index].forage_specs_id) {
              ADDtrue.value = false

              return ElMessage('请选择饲料规格')
            } else if (!formData.detailed[index].forage_id) {
              ADDtrue.value = false

              return ElMessage('请选择饲料档案')
            } else if (formData.type == '1' && !formData.detailed[index].amount) {
              ADDtrue.value = false

              return ElMessage('请填入采购金额')
            } else if (formData.type == '2' && !formData.detailed[index].apply_number) {
              ADDtrue.value = false

              return ElMessage('请填入申请数量')
            }
            const GG = await spForageSpecsSeeApi({ id: formData.detailed[index].forage_specs_id })
            if (
              Number(GG.data.available_stock) - Number(formData.detailed[index].apply_number) < 0 &&
              formData.type == '2'
            ) {
              console.log('添加不了')
              ElNotification({
                title: '通知',
                message: h(
                  'i',
                  { style: 'color: teal' },
                  '出库数量不足，从新选择或者修改数量！！！'
                )
              })
              ADDtrue.value = false
              break
            }
          }
          if (ADDtrue.value) {
            let res = await spForageInOutOrderAddAdminApi({
              my_dept_id: userInfo.default_dept_id,
              pasture_org_id: formData.pasture_org_id,
              pasture_dept_id: formData.pasture_dept_name,
              operate_id: formData.operate_name,
              type: formData.type,
              in_type: formData.in_type,
              out_type: formData.out_type,
              note: formData.note,
              detailed: formData.detailed
            })
              .catch(() => {})
              .finally(() => {
                // saveLoading.value = false
              })
            if (res) {
              dialogVisible.value = false
              tableObject.currentPage = 1
              getList()
            }
          }
        }
      })

      break
    default:
      console.log('未知类型')
  }
}

// watch(
//   () => tableObject.tableList,
//   async (val: any) => {
//     if (!val) return
//     // 设置固定条件
//     for (let index = 0; index < tableObject.tableList.length; index++) {
//       const res: any = await spForageInOutOrderSeeApi({ id: tableObject.tableList[index].id })
//         .catch(() => {})
//         .finally(() => {})
//       // if (res) {
//       //   data.value = res.data
//       // }
//       let num = ref(0)
//       for (let i = 0; i < res.data.detailed.length; i++) {
//         num.value = +res.data.detailed[i].apply_number + num.value
//       }
//       tableObject.tableList[index].sum = num.value
//       // console.log(tableObject.tableList, index, res.data.detailed, num.value)
//     }
//   },
//   {
//     deep: true,
//     immediate: true
//   }
// )
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">新增</ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
      :selection="false"
    >
      <template #action="{ row }">
        <ElButton
          v-if="row.state == 1"
          circle
          :icon="iconEdit"
          @click="action('edit', row)"
          title="修改主表"
        />

        <ElButton
          v-if="row.state == 1"
          circle
          :icon="row.type == 1 ? iconEnter : iconGo"
          @click="action('ming', row)"
          title="修改明细"
        />
        <ElButton circle :icon="iconSee" @click="action('see', row)" title="查看" />

        <ElButton
          v-if="row.state == 1"
          circle
          :icon="iconDelete"
          @click="action('del', row)"
          title="删除"
        />
        <ElButton
          v-if="row.state == 1"
          circle
          :icon="iconCompleted"
          @click="action('shen', row)"
          title="确认归档"
        />

        <ElButton
          v-if="row.state == 2"
          circle
          :icon="iconExport"
          @click="action('export', row)"
          title="明细导出"
        />
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Add v-if="actionType == 'edit'" ref="editRef" :id="tableObject.currentRow.id" />

    <See
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
      :id="tableObject.currentRow.id"
    />

    <See
      v-if="actionType == 'shen'"
      ref="editRef"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
      :id="tableObject.currentRow.id"
    />

    <Add
      v-if="actionType == 'add'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
      ref="editRef"
    />

    <Edit
      v-if="actionType == 'ming'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
      :id="tableObject.currentRow.id"
    />
    <template #footer>
      <!-- <ElButton
        v-if="actionType !== 'see' && actionType !== 'add'"
        type="primary"
        :loading="loading"
        @click="save()"
      >
        {{ t('exampleDemo.save') }}
      </ElButton> -->
      <ElButton
        v-if="actionType == 'add' || actionType == 'edit' || actionType == 'shen'"
        type="primary"
        :loading="loading"
        @click="save()"
      >
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
